<script lang="ts" setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {useRoute} from 'vue-router'
import {handleError} from '@/utils/message'
import {PICTURE} from '@/constants/messages'
import {DownloadOutlined, EyeOutlined, SearchOutlined} from '@ant-design/icons-vue'
import MainLayout from '@/components/layout/MainLayout.vue'
import ProgressiveImage from '@/components/common/ProgressiveImage.vue'
import {pictureApi} from '@/api'
import {useAuthStore} from '@/stores/modules/auth'
import type {PictureVO} from '@/types/vo/picture'
import {PICTURE_CATEGORIES} from '@/constants/picture'

const route = useRoute()
const authStore = useAuthStore()

const pictureList = ref<PictureVO[]>([])
const pagination = reactive({
  current: 1,
  size: 12,
  total: 0
})

const loading = ref(false)
const searchParams = reactive({
  keyword: (route.query.q as string) || '',
  category: undefined as string | undefined,
  tag: ''
})

const loadPictures = async () => {
  loading.value = true
  try {
    const keyword = searchParams.keyword?.trim()
    const tag = searchParams.tag?.trim()

    const result = await pictureApi.list({
      current: pagination.current,
      size: pagination.size,
      searchText: keyword || undefined,
      category: searchParams.category,
      tag: tag || undefined,
      reviewStatus: 1
    })

    pictureList.value = result.records
    pagination.total = result.total
  } catch (error: any) {
    handleError(error, PICTURE.LOAD_FAILED)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadPictures()
}

const handlePageChange = () => {
  loadPictures()
  window.scrollTo({top: 0, behavior: 'smooth'})
}

watch(() => route.query.q, (newVal) => {
  if (newVal) {
    searchParams.keyword = newVal as string
    handleSearch()
  }
})

const handleTagClick = (tag: string) => {
  searchParams.tag = tag
  searchParams.keyword = ''
  handleSearch()
}

const clearTag = () => {
  searchParams.tag = ''
  handleSearch()
}

onMounted(() => {
  loadPictures()
})
</script>

<template>
  <main-layout>
    <div class="explore-container">
      <!-- 搜索和筛选区 -->
      <div class="filter-section">
        <a-card>
          <a-space :size="16" direction="vertical" style="width: 100%">
            <a-input-search
                v-model:value="searchParams.keyword"
                enter-button
                placeholder="搜索图片..."
                size="large"
                @search="handleSearch"
            >
              <template #prefix>
                <SearchOutlined/>
              </template>
            </a-input-search>

            <a-space wrap>
              <a-select
                  v-model:value="searchParams.category"
                  placeholder="选择分类"
                  style="width: 150px"
                  @change="handleSearch"
              >
                <a-select-option :value="undefined">全部分类</a-select-option>
                <a-select-option
                    v-for="cat in PICTURE_CATEGORIES"
                    :key="cat.value"
                    :value="cat.value"
                >
                  {{ cat.label }}
                </a-select-option>
              </a-select>
            </a-space>
          </a-space>

          <!-- 当前筛选标签 -->
          <div v-if="searchParams.tag" class="active-filters">
            <span style="margin-right: 8px; color: #666;">当前筛选：</span>
            <a-tag closable color="blue" @close="clearTag">
              {{ searchParams.tag }}
            </a-tag>
          </div>
        </a-card>
      </div>

      <!-- 图片网格 -->
      <a-spin :spinning="loading">
        <div v-if="pictureList.length > 0" class="pictures-grid">
          <div
              v-for="picture in pictureList"
              v-show="picture.id"
              :key="picture.id"
              class="picture-item"
          >
            <router-link :to="`/picture/${picture.id}`" class="picture-link">
              <div class="picture-cover">
                <progressive-image
                    :alt="picture.pictureName"
                    :lazy="true"
                    :src="picture.thumbnailUrl || picture.fileUrl"
                />
                <div class="picture-mask">
                  <a-space>
                    <span><EyeOutlined/> {{ picture.viewCount || 0 }}</span>
                    <span><DownloadOutlined/> {{ picture.downloadCount || 0 }}</span>
                  </a-space>
                </div>
              </div>
              <div class="picture-meta">
                <div class="picture-title">{{ picture.pictureName }}</div>
                <div class="picture-author">
                  <a-avatar :size="24" :src="picture.user?.userAvatar">
                    {{ picture.user?.userName?.charAt(0) || 'U' }}
                  </a-avatar>
                  <span>{{ picture.user?.userName || '匿名' }}</span>
                </div>
              </div>
            </router-link>
            <!-- 标签（在链接外部，避免冲突） -->
            <div v-if="picture.tags && picture.tags.length > 0" class="picture-tags">
              <a-tag
                  v-for="tag in picture.tags.slice(0, 3)"
                  :key="tag"
                  class="tag-item"
                  size="small"
                  @click.stop="handleTagClick(tag)"
              >
                {{ tag }}
              </a-tag>
            </div>
          </div>
        </div>

        <a-empty v-else description="暂无图片，快去上传第一张图片吧！" style="margin: 60px 0">
          <template #footer>
            <a-button v-if="authStore.isLoggedIn" type="primary" @click="$router.push('/picture/upload')">
              立即上传
            </a-button>
            <a-button v-else type="primary" @click="$router.push('/login')">
              登录后上传
            </a-button>
          </template>
        </a-empty>

        <!-- 分页 -->
        <div v-if="pagination.total > 0" class="pagination">
          <a-pagination
              v-model:current="pagination.current"
              v-model:page-size="pagination.size"
              :show-total="(total: number) => `共 ${total} 张图片`"
              :total="pagination.total"
              show-size-changer
              @change="handlePageChange"
          />
        </div>
      </a-spin>
    </div>
  </main-layout>
</template>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as *;
@use '@/assets/styles/components.scss' as *;

.explore-container {
  @include container;
  padding: $spacing-xl $spacing-lg;

  @include responsive($breakpoint-md) {
    padding: $spacing-lg $spacing-md;
  }
}

.filter-section {
  @include filter-section;

  .active-filters {
    margin-top: $spacing-md;
    padding-top: $spacing-md;
    border-top: 1px solid $border-light;
    display: flex;
    align-items: center;

    span {
      font-weight: $font-medium;
      color: $text-secondary;
    }

    :deep(.ant-tag) {
      font-weight: $font-medium;
    }
  }
}

.pictures-grid {
  @include pictures-grid;
}

.picture-item {
  @include picture-card;

  .picture-cover {
    :deep(.progressive-image) {
      width: 100%;
      border-radius: 0;
    }
  }

  .picture-tags {
    padding: $spacing-sm $spacing-lg $spacing-md;
    display: flex;
    flex-wrap: wrap;
    gap: $spacing-xs;

    .tag-item {
      cursor: pointer;
      transition: $transition-all;
      font-size: $font-xs;

      &:hover {
        transform: scale(1.08);
        opacity: 0.85;
      }
    }
  }
}

.pagination {
  @include pagination;
}
</style>